package com.seeyon.apps.attendance.quartz;

import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.seeyon.apps.attendance.data.DingdingOrgData;
import com.seeyon.apps.quartz.abstra.AbstractQuartzTask;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormBindAuthBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ModuleType;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.content.mainbody.MainbodyManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.content.CtpContentAll;
import com.seeyon.ctp.login.UserUtil;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;

import java.util.*;

import static com.seeyon.apps.quartz.util.CAP4FormKit.getFieldTaleId;


/**
 * @Author: S
 * @Date: 2022/6/21 15:15
 * @Description:定时更新数据
 */
public class InAdvanceWriteQuartz extends AbstractQuartzTask {
    private MainbodyManager ctpMainbodyManager;
    private DingdingOrgData dingdingOrgData;
    private OrgManager orgManager;

    {
        this.dingdingOrgData = new DingdingOrgData();
    }
    private MainbodyManager getCtpMainbodyManager() {
        if (null == ctpMainbodyManager) {
            ctpMainbodyManager = (MainbodyManager) AppContext.getBean("ctpMainbodyManager");
        }
        return ctpMainbodyManager;
    }

    private OrgManager getOrgManager() {
        if (null == orgManager) {
            orgManager = (OrgManager) AppContext.getBean("orgManager");
        }
        return orgManager;
    }

    @Override
    public String taskRun(String param) throws Exception {
        //获取打卡档案
        FormBean formBean = getFormApi4Cap4().getFormByFormCode("CheckFromDing");
        ArrayList<Date> allTheDateOfTheMonth = getAllTheDateOfTheMonth(new Date());
        dingdingOrgData.getToken();
        User superNodeUser = UserUtil.buildVirtualUser(97979797l, "QuartzFormUser");
        UserUtil.setCurrentUser(superNodeUser);
        List<OapiDepartmentListResponse.Department> departmentList = dingdingOrgData.getDepartmentList();
        HashMap<String, OapiV2UserListResponse.ListUserResponse> map = new HashMap<>();
        ArrayList<String> userIds = new ArrayList<>();
        //遍历获取人员信息
        for (OapiDepartmentListResponse.Department department : departmentList) {
            OapiV2UserListResponse userList = dingdingOrgData.getUserList(department.getId(), 0L);
            OapiV2UserListResponse.PageResult result = userList.getResult();
            Long nextCursor = result.getNextCursor();
            List<OapiV2UserListResponse.ListUserResponse> list = result.getList();
            list.forEach(element -> {
                map.put(element.getUserid(), element);
            });
            if (null != nextCursor) {
                getUserInfoByDept(department, nextCursor, formBean, userIds, map);
            }
        }
        ArrayList<V3xOrgMember> oaUsers = getOaUser(map, userIds);
        for (int i = 0; i < oaUsers.size(); i++) {
            V3xOrgMember v3xOrgMember = oaUsers.get(i);
            for (int j = 0; j < allTheDateOfTheMonth.size(); j++) {
                Date date = allTheDateOfTheMonth.get(j);
                FormTableBean masterTableBean = formBean.getMasterTableBean();
                FormDataMasterBean master = new FormDataMasterBean(masterTableBean);
                master.addFieldValue(getFieldTaleId(formBean, "姓名"), v3xOrgMember.getId());
                master.addFieldValue(getFieldTaleId(formBean, "考勤日期"), date);
                saveContent(formBean,master);
            }
        }

        return "每月预写入数据";
    }

    /**
     * 根据手机号获取OA人员信息
     *
     * @param userIds
     */
    private ArrayList<V3xOrgMember> getOaUser(HashMap<String, OapiV2UserListResponse.ListUserResponse> map, ArrayList<String> userIds) {
        ArrayList<V3xOrgMember> users = new ArrayList<>();
        map.values().forEach(userInfo -> {
            if (!userIds.contains(userInfo.getUserid())) {
                userIds.add(userInfo.getUserid());
                V3xOrgMember membersByMobile = null;
                try {
                    membersByMobile = getOrgManager().getMembersByMobile(userInfo.getMobile(), V3xOrgEntity.VIRTUAL_ACCOUNT_ID);
                } catch (BusinessException e) {
                    log.error("通过手机号获取人员失败", e);
                }
                if (null != membersByMobile) {
                    users.add(membersByMobile);
                } else {
                    log.info("根据手机号查询人员失败，名字为:" + userInfo.getName() + "----钉钉手机号为:" + userInfo.getMobile());
                }
            }
        });
        return users;
    }

    /**
     * 获取用户id列表
     *
     * @param department
     * @param nextCursor
     * @param formBean
     * @param userIds
     */
    private void getUserInfoByDept(OapiDepartmentListResponse.Department department, Long nextCursor, FormBean formBean, ArrayList<String> userIds, HashMap<String, OapiV2UserListResponse.ListUserResponse> map) {
        OapiV2UserListResponse userList = dingdingOrgData.getUserList(department.getId(), 0L);
        OapiV2UserListResponse.PageResult result = userList.getResult();
        Long nextCursor2 = result.getNextCursor();
        List<OapiV2UserListResponse.ListUserResponse> list = result.getList();
        list.forEach(element -> {
            map.put(element.getUserid(), element);
        });
        if (null != nextCursor) {
            getUserInfoByDept(department, nextCursor2, formBean, userIds, map);
        }
    }






    private static ArrayList<Date> getAllTheDateOfTheMonth(Date date) {
        ArrayList<Date> list = new ArrayList();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.DATE, 1);
        cal.add(Calendar.MONTH, 1);
        int month = cal.get(Calendar.MONTH);
        while(cal.get(Calendar.MONTH) == month){
            list.add(cal.getTime());
            cal.add(Calendar.DATE, 1);
        }
        return list;
    }

    private void saveContent(FormBean formBean, FormDataMasterBean master) {
        List<CtpContentAll> contentAlls = new ArrayList<>();
        Long memberId = AppContext.getCurrentUser().getId();
        Map<String, Object> contentParams = new HashMap<>();
        contentParams.put("moduleType", ModuleType.cap4UnflowForm.getKey());
        FormBindAuthBean auth = null;
        Map<String, FormBindAuthBean> authBeans = formBean.getBind().getUnFlowTemplateMap();
        for (String key : authBeans.keySet()) {
            auth = authBeans.get(key);
            break;
        }
        contentParams.put("moduleId", Long.valueOf(auth.getId()));
        List<CtpContentAll> contentPoList = getCtpMainbodyManager().getContentList(contentParams);
// 保存ctp_content_all
        Long moduleTemplateId;
        if (null != contentPoList && contentPoList.size() > 0) {
            moduleTemplateId = contentPoList.get(0).getId();
        } else {
            log.info("没有获取到contentPoList数据");
            moduleTemplateId = auth.getId();
        }
        CtpContentAll contentAll = getContentAll(memberId, moduleTemplateId, master.getId(), formBean);
        contentAlls.add(contentAll);
        try {
            getCtpMainbodyManager().saveAll(contentAlls);
            getFormApi4Cap4().saveOrUpdateFormData(master, formBean.getId(), true);
        } catch (Exception e) {
            log.error("保存正文数据异常：", e);
        }
    }

    private CtpContentAll getContentAll(Long memberId, Long moduleTemplateId, Long masterId, FormBean bean) {
        CtpContentAll ctpContentAll = new CtpContentAll();
        ctpContentAll.setIdIfNew();
        ctpContentAll.setModuleTemplateId(moduleTemplateId);
        ctpContentAll.setModuleType(ModuleType.cap4UnflowForm.getKey());
        ctpContentAll.setModuleId(masterId);
        ctpContentAll.setContentType(20);
        ctpContentAll.setContentTemplateId(bean.getId());
        ctpContentAll.setModifyId(memberId);
        ctpContentAll.setModifyDate(new Date());
        ctpContentAll.setContentDataId(masterId);
        ctpContentAll.setCreateId(memberId);
        ctpContentAll.setCreateDate(new Date());
        ctpContentAll.setSort(0);
        return ctpContentAll;
    }
}
